import logging

from flask import Blueprint, render_template, request, redirect, url_for, flash, g, jsonify
from blueprints.forms import QuestionForm, AnswerForm
from decorators import check_login
from exts import db
from models import QuestionModel, AnswerModel

# 创建蓝图对象
blueprints = Blueprint('qa', __name__, url_prefix='/')


@blueprints.route('/')
def index():
    questions = QuestionModel.query.order_by(QuestionModel.join_time.desc()).all()
    return render_template('index.html', questions=questions)


@blueprints.route('/qa/public', methods=['GET', 'POST'])
@check_login
def public_qa():
    if request.method == 'POST':
        try:
            form = QuestionForm(request.form)
            if form.validate():
                flash('提交成功')
                title = form.title.data
                content = form.content.data
                question = QuestionModel(title=title, content=content, author=g.current_user)
                db.session.add(question)
                db.session.commit()
                return redirect(url_for('qa.index'))
            flash('提交失败')
            return jsonify({'code': 400, 'msg': '填写错误', 'error': form.errors})
        except Exception as e:
            flash('提交失败')
            db.session.rollback()
            return jsonify({'code': 400, 'msg': '提交失败', 'error': str(e)})

    return render_template('public_qa.html')


@blueprints.route('/qa/detail/<int:qa_id>')
def detail_qa(qa_id):
    question = QuestionModel.query.get(qa_id)
    if question:
        return render_template('detail_qa.html', question=question)
    flash('问题不存在')
    return redirect(url_for('qa.index'))


@blueprints.route('/answer/public', methods=['POST'])
@check_login
def public_answer():
    form = AnswerForm(request.form)
    if form.validate:
        try:
            content = form.content.data
            question_id = form.question_id.data
            answer = AnswerModel(content=content, question_id=question_id, author=g.current_user)
            db.session.add(answer)
            db.session.commit()
            return redirect(url_for('qa.detail_qa', qa_id=question_id))

        except Exception as e:
            logging.error(e)
            db.session.rollback()
            return jsonify({'code': 400, 'msg': '提交失败', 'error': str(e)})
    return jsonify({'code': 400, 'msg': '填写错误', 'error': form.errors})


@blueprints.route('/search')
@check_login
def search():
    keyword = request.args.get('keyword')
    questions = QuestionModel.query.filter(QuestionModel.title.like('%{}%'.format(keyword))).all()
    return render_template('index.html', questions=questions)
